package com.nxn.core.web.action.security;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.nxn.core.model.Resources;
import com.nxn.core.model.RoleAuth;
import com.nxn.core.model.User;
import com.nxn.core.service.UserService;
import com.nxn.core.web.action.base.BaseAction;

@Controller("loginAction")
@Scope("prototype")
@Results({
	@Result(name="login", location="login.jsp"),
	@Result(name="success", location="/WEB-INF/content/admin.jsp")
	})
public class LoginAction extends BaseAction {
	private static final long serialVersionUID = 5220029489994041242L;
	
	private User user;
	private String kaptcha;
	private boolean rememberMe;

	@Autowired
	private Producer captchaProducer = null;  
	@Autowired
	private UserService userService;
	@Autowired
	private JavaMailSender mailSender;
	
	public String captchaImage() throws Exception {

		getResponse().setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		getResponse().setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		getResponse().addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		getResponse().setHeader("Pragma", "no-cache");
		// return a jpeg
		getResponse().setContentType("image/jpeg");
		// create the text for the image
		String capText = captchaProducer.createText();
		// store the text in the session
		getSession(false).setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		// create the image with the text
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = getResponse().getOutputStream();
		// write the data out
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		
		return null;
	}	
	
	@Action(value="/dwz/login", results={@Result(name="success", location="/WEB-INF/content/dwz/testAdmin_dwz.jsp")})
	public String login() throws Exception {
		
		//String code = (String)getSession(false).getAttribute(Constants.KAPTCHA_SESSION_KEY);
		
/*		if(!code.equals(getKaptcha())) {
			getRequest().setAttribute("message", "验证码错误");
			return "login";
		}*/
		
		Boolean rememberMe = true;
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token;
			if (null == rememberMe)
				// token = new UsernamePasswordToken(user.getUsername(),
				// EncryptUtils.encodeMD5String(user.getPassword()),false,request.getRemoteAddr());
				// else token = new UsernamePasswordToken(user.getUsername(),
				// EncryptUtils.encodeMD5String(user.getPassword()), true,
				// request.getRemoteAddr());
				token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
			else
				token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
			try {
				currentUser.login(token);
			} catch (AuthenticationException ae) {
				getRequest().setAttribute("message", "用户名密码错误");
				return "login";
			}
		}
		buildResourceMenu();
		
		return SUCCESS;
	}
	
	private void buildResourceMenu() {
	    List<Resources> resources = new ArrayList<Resources>();
		
    	List<RoleAuth> menuResources = userService.findMenuResourceByUsername(user.getUsername());
    	for (Iterator<RoleAuth> iter = menuResources.iterator(); iter.hasNext();) {
			RoleAuth roleAuth = iter.next();
			resources.add(roleAuth.getResource());
		}
    	
    	getRequest().setAttribute("resources", resources);
	}

	public String logout() throws Exception {
		Subject currentUser = SecurityUtils.getSubject();
		
        if (currentUser != null) {
        	currentUser.logout();
        }
        
        if(getSession(false) != null) {
        	getSession(false).invalidate();
        }
        
		return "login";
	}
	
	public String sendMail() {
		Subject currentUser = SecurityUtils.getSubject();

		if (currentUser.isPermitted("users:query")) {
		    System.out.println("permitted");
		} else {
		    System.out.println("not permitted");
		}
		
		//注意SimpleMailMessage只能用来发送text格式的邮件
		SimpleMailMessage mail = new SimpleMailMessage();

		try {
			mail.setTo("zhangleizlpd@sina.com");// 接受者
			mail.setFrom("zhangleizlpd@163.com");// 发送者,这里还可以另起Email别名，不用和xml里的username一致
			mail.setSubject("spring mail test!");// 主题
			mail.setText("springMail的简单发送测试");// 邮件内容
			
			mailSender.send(mail);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getKaptcha() {
		return kaptcha;
	}

	public void setKaptcha(String kaptcha) {
		this.kaptcha = kaptcha;
	}

	public boolean getRememberMe() {
		return rememberMe;
	}

	public void setRememberMe(boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

}
